package tk.chenyilin.server;

import java.io.StringReader;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 用于提取xml中的信息并予以进行操作
 */
public class ExtractInfo {

	Connection connection;

	DocumentFactory factory = DocumentFactory.getInstance();

	SAXReader reader = new SAXReader();

	public ExtractInfo(Connection connection) {
		this.connection = connection;
	}

	void work(String xml) throws Exception {
		try {
			Document doc = reader.read(new StringReader(xml));
			Element root = doc.getRootElement();
			String type = root.attributeValue("type"); // xml类型

			switch (type) {
			case Connection.LOGIN: // 客户端登录信息
				loginInfo(root);
				break;
			case Connection.MESSAGE: // 客户端发消息
				sendBack(doc);
				break;
			case Connection.EXIT: // 客户端推出
				clientExit(root);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	void clientExit(Element root) throws Exception {
		String username = root.elementText("user");
		connection.server.model.removeElement(username);
		connection.server.map.remove(username);
		sendUserList();
	}

	void loginInfo(Element root) throws Exception {
		String username = root.elementText("username");
		if (connection.server.map.containsKey(username))
		/*
		 * 判断是否已有这个用户名，如果有，则返回错误信息
		 */{
			Element element = factory.createElement("message");
			element.addAttribute("type", "1");
			element.add(factory.createElement("response").addText("failure"));
			Document xmlSentBack = factory.createDocument(element);
			connection.os.write(xmlSentBack.asXML().getBytes());
			connection.server.print("another \"" + username
					+ "\" wants to join in but was refused");
		} else {
			/*
			 * 否则添加这个新用户
			 */
			connection.server.map.put(username, new User(connection.is,
					connection.os, username));
			connection.server.model.addElement(username);
			Element element = factory.createElement("message");
			element.addAttribute("type", "1");
			element.add(factory.createElement("response").addText("success"));
			Document xmlSentBack = factory.createDocument(element);
			connection.os.write(xmlSentBack.asXML().getBytes());
			connection.server.print(username + " has joined in.");
			/*
			 * 等待2秒，让流中的信息分两条发送。
			 * 否则会出现两条xml被放在一个String中，导致解析失败
			 */
			Thread.sleep(2000);	
			sendUserList();
		}
	}

	// 向所有用户发送用户列表
	void sendUserList() throws Exception {
		Document doc = factory.createDocument();
		Element root = factory.createElement("message").addAttribute("type",
				Connection.USER_LIST);
		for (int i = 0; i < connection.server.model.getSize(); i++) {
			String username = connection.server.model.elementAt(i);
			root.add(factory.createElement("user").addText(username));
		}
		doc.add(root);
		for (User user : connection.server.map.values()) {
			user.os.write(doc.asXML().getBytes());
		}
	}

	// 直接发回用户发来的文本信息
	void sendBack(Document doc) throws Exception {
		String xml = doc.asXML();
		for (User user : connection.server.map.values()) {
			user.os.write(xml.getBytes());
		}
	}
}
